package com.example.demo01.Service;

import com.example.demo01.Entity.Client;
import com.example.demo01.Entity.Tag;
import com.example.demo01.Repository.ClientRepository;
import com.example.demo01.Repository.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TagService {

    @Autowired
    private TagRepository tagRepository;

    @Autowired
    private ClientRepository clientRepository;

    // 添加标签到客户
    public Tag addTagToClient(Long clientId, String labelName) {
        // 查找客户
        // 打印 clientId 进行调试
        System.out.println("Received client ID: " + clientId);

        // 查找客户
        Client client = clientRepository.findById(clientId)
                .orElseThrow(() -> new RuntimeException("Client not found with ID: " + clientId));
        // 创建新的标签
        Tag tag = new Tag(labelName, client);

        // 保存标签并返回
        return tagRepository.save(tag);
    }

    // 根据客户ID查询所有标签
    public List<Tag> getTagsByClientId(Long clientId) {
        return tagRepository.findByClientId(clientId);
    }

    // 根据客户ID删除所有标签
    public void deleteTagsByClientId(Long clientId) {
        List<Tag> tags = tagRepository.findByClientId(clientId);
        tagRepository.deleteAll(tags);
    }


public List<Client> getClientsByType(String type) {
    if ("new".equals(type)) {
        // 查询新客户（比如基于标签或创建时间）
        return clientRepository.findByTags_LabelName("新客户");
    }else if("old".equals(type)){
        return clientRepository.findByTags_LabelName("老客户");
    }
    return clientRepository.findAll();  // 默认查询所有客户
}

}
